package com.db.gffxo.epi.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.context.ApplicationContext;

import com.db.gffxo.epi.domain.Event;
import com.db.gffxo.epi.domain.EventDetail;
import com.db.gffxo.epi.publish.Publisher;

public class PublishController implements Controller {

	boolean shutdown = false;
	PublishControllerServices services = null;
	ApplicationContext applicationContext = null;
	
	
	public void run() {
		// TODO Auto-generated method stub

		services.loadPublishers(applicationContext);
		
		while (!shutdown) {
			List<EventDetail> events = services.getEventDetailBatch();
			EventDetail eventDetail = null;
			Event event = null;
			Iterator<EventDetail> it = events.iterator();
			while (it.hasNext()) {
				try {
					eventDetail = it.next();
					event = eventDetail.getEvent();
					event.setStatus(Event.STATUS_Sending+eventDetail.getDetailId());
					services.updatePublishedEvent(eventDetail, true);
					event.setStatus(Event.STATUS_NoPublisher);
					ArrayList<Publisher> pblshers = services.getPublisher(eventDetail.getEvent().getEventType());
					for (int i=0;i<pblshers.size();i++) {
						Publisher pub = pblshers.get(i);
						if (pub.getFormatList().contains(eventDetail.getFormatterId())) {
							pub.publishEvent(eventDetail.getMessage());							
							event.setStatus(Event.STATUS_Sent);
						}
					}
					services.updatePublishedEvent(eventDetail, true);							
				} catch (Exception e) {
					//TODO -  Do we shutdown or continue 
					services.updatePublishedEvent(eventDetail, false);
				}
			}
			try {
				if (events.size()==0)
					Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				shutdown=true;
			}
		}			
}


	public PublishControllerServices getServices() {
		return services;
	}


	public void setServices(PublishControllerServices services) {
		this.services = services;
	}


	//getAppplicationContext();
	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}


	//setAppplicationContext(rs.getApplicationContext(10));
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}
	
}